#include <STC15F2K60S2.H>
#include "Tim.h"
#include "Seg.h"
#include "LED.h"
#include "Key.h"
#include "stdio.h"
#include "PWM.h"
sbit Pwm_Out = P3^4;
unsigned char pucSeg_Buf[9],pucSeg_Code[8],ucSeg_Pos;
unsigned int ucSeg_Dly;
unsigned long ulms;
unsigned char ucKey_Dly,ucKey_Old;
unsigned char ucState=0;
unsigned char ucCount, ucPwm; 
unsigned char ucLed;
void Seg_Proc(void);
void Key_Proc(void) ;
void main(){
	Cls_Peripheral() ;
	Timer1Init();
	Timer0Init();
	while(1){
		Key_Proc();
		Seg_Proc();
}
}
void Time_1(void) interrupt 3 //定时器1中断函数
{ 
	 ulms++; 
	 if(!(ulms % 1000)) { 
		 
	} 
	 if(++ucSeg_Dly==10) ucSeg_Dly=0;
	 if(++ucKey_Dly==20) ucKey_Dly=0;
	 Seg_Disp(pucSeg_Code, ucSeg_Pos);
	if(++ucSeg_Pos==8) ucSeg_Pos=0;
}
void Time_0(void) interrupt 1{
	if(++ucCount==10) ucCount=0;//100等份的时候，信号频率为100HZ，这里是1ms，频率是1khz
	if(ucPwm){
			if(!ucCount){
		Pwm_Out=1;
		ucLed |= 0x80;
	}
	else if(ucCount==ucPwm){
		Pwm_Out = 0; 
		ucLed &= 0x7F;
	}
}
//	else
//		ucLed &= 0x7f; 
	Led_Disp(ucLed); 

}
void Key_Proc(void) 
{ 
	 unsigned char ucKey_Val, ucKey_Down, ucKey_Up; 
	 if(ucKey_Dly) return; 
		ucKey_Dly = 1; 
	 ucKey_Val = Key_Read(); 
	 ucKey_Down = ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Up = ~ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Old = ucKey_Val; 
	 if(ucKey_Down==4)  { 
		 ucState++;
		 ucState%=3;
	 } 
}
void Seg_Proc(void){
	if(ucSeg_Dly) return;
	ucSeg_Dly=1;
	switch(ucState){
		case 0:
			//Led_Disp(0) ;
		ucLed &= 0x7f; 
		Led_Disp(ucLed); 
		ucPwm=0;
			sprintf(pucSeg_Buf,"%d",(unsigned int)ucState);
		break;
		case 1:
			ucPwm=5;
			sprintf(pucSeg_Buf,"%d",(unsigned int)ucState);
			break;
		case 2:
			ucPwm=10;
			sprintf(pucSeg_Buf,"%d",(unsigned int)ucState);
			break;
	}
	Seg_Tran(pucSeg_Buf, pucSeg_Code);
}